import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'user_model.dart';
import '../../core/http/http_client.dart';

class UserForm extends StatefulWidget {
  final UserModel? user;
  final Function(Map<String, dynamic>) onSubmit;

  const UserForm({
    Key? key,
    this.user,
    required this.onSubmit,
  }) : super(key: key);

  @override
  _UserFormState createState() => _UserFormState();
}

class _UserFormState extends State<UserForm> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _nicknameController = TextEditingController();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _phoneController = TextEditingController();
  final _remarkController = TextEditingController();
  bool _isActive = true;
  File? _avatarFile;
  List<RoleModel> _selectedRoles = [];
  List<RoleModel> _availableRoles = [];
  final _httpClient = HttpClient();

  @override
  void initState() {
    super.initState();
    if (widget.user != null) {
      _usernameController.text = widget.user!.username;
      _nicknameController.text = widget.user!.nickname;
      _emailController.text = widget.user!.email;
      _phoneController.text = widget.user!.phone ?? '';
      _remarkController.text = widget.user!.remark ?? '';
      _isActive = widget.user!.isActive;
      _selectedRoles = List.from(widget.user!.roles);
    }
    _loadRoles();
  }

  Future<void> _loadRoles() async {
    try {
      final response = await _httpClient.get('/roles');
      if (response.code == 200) {
        final data = response.data['data'] as List;
        _availableRoles = data.map((json) => RoleModel.fromJson(json)).toList();
        setState(() {});
      } else {
        // 如果加载失败，使用默认角色
        _availableRoles = [
          RoleModel(id: 1, name: '管理员'),
          RoleModel(id: 2, name: '运营经理'),
          RoleModel(id: 3, name: '运营人员'),
          RoleModel(id: 4, name: '销售人员'),
        ];
        setState(() {});
      }
    } catch (e) {
      // 如果发生错误，使用默认角色
      _availableRoles = [
        RoleModel(id: 1, name: '管理员'),
        RoleModel(id: 2, name: '运营经理'),
        RoleModel(id: 3, name: '运营人员'),
        RoleModel(id: 4, name: '销售人员'),
      ];
      setState(() {});
    }
  }

  Future<void> _pickImage() async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _avatarFile = File(image.path);
      });
    }
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _nicknameController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _phoneController.dispose();
    _remarkController.dispose();
    super.dispose();
  }

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      final userData = {
        'username': _usernameController.text,
        'nickname': _nicknameController.text,
        'email': _emailController.text,
        'phone': _phoneController.text,
        'remark': _remarkController.text,
        'status': _isActive?1:0,
        'roles': _selectedRoles.map((role) => role.id).toList(),
      };

      // 只在创建新用户时或密码字段有值时添加密码
      if (widget.user == null || _passwordController.text.isNotEmpty) {
        userData['password'] = _passwordController.text;
      }

      // 如果有新的头像文件，添加到表单数据中
      if (_avatarFile != null) {
        userData['avatar'] = _avatarFile!;
      }

      widget.onSubmit(userData);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 头像选择
          Center(
            child: Stack(
              children: [
                CircleAvatar(
                  radius: 50,
                  backgroundImage: _avatarFile != null
                      ? FileImage(_avatarFile!)
                      : (widget.user?.avatar != null
                          ? NetworkImage(widget.user!.avatar!)
                          : null) as ImageProvider?,
                  child: _avatarFile == null && widget.user?.avatar == null
                      ? const Icon(Icons.person, size: 50)
                      : null,
                ),
                Positioned(
                  bottom: 0,
                  right: 0,
                  child: CircleAvatar(
                    backgroundColor: Theme.of(context).primaryColor,
                    child: IconButton(
                      icon: const Icon(Icons.camera_alt, color: Colors.white),
                      onPressed: _pickImage,
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
          
          // 用户名
          TextFormField(
            controller: _usernameController,
            decoration: const InputDecoration(
              labelText: '用户名',
              hintText: '请输入用户名',
              prefixIcon: Icon(Icons.person),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入用户名';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 昵称
          TextFormField(
            controller: _nicknameController,
            decoration: const InputDecoration(
              labelText: '昵称',
              hintText: '请输入昵称',
              prefixIcon: Icon(Icons.badge),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入昵称';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 邮箱
          TextFormField(
            controller: _emailController,
            decoration: const InputDecoration(
              labelText: '邮箱',
              hintText: '请输入邮箱',
              prefixIcon: Icon(Icons.email),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入邮箱';
              }
              if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
                return '请输入有效的邮箱地址';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 密码
          TextFormField(
            controller: _passwordController,
            decoration: InputDecoration(
              labelText: widget.user == null ? '密码' : '新密码（留空表示不修改）',
              hintText: widget.user == null ? '请输入密码' : '请输入新密码',
              prefixIcon: const Icon(Icons.lock),
            ),
            obscureText: true,
            validator: (value) {
              if (widget.user == null && (value == null || value.isEmpty)) {
                return '请输入密码';
              }
              if (value != null && value.isNotEmpty && value.length < 6) {
                return '密码长度不能少于6位';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 手机号
          TextFormField(
            controller: _phoneController,
            decoration: const InputDecoration(
              labelText: '手机号',
              hintText: '请输入手机号',
              prefixIcon: Icon(Icons.phone),
            ),
            validator: (value) {
              if (value != null && value.isNotEmpty) {
                if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
                  return '请输入有效的手机号码';
                }
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 备注
          TextFormField(
            controller: _remarkController,
            decoration: const InputDecoration(
              labelText: '备注',
              hintText: '请输入备注信息',
              prefixIcon: Icon(Icons.note),
            ),
            maxLines: 3,
          ),
          const SizedBox(height: 16),
          
          // 角色选择
          const Text('角色', style: TextStyle(fontSize: 16)),
          const SizedBox(height: 8),
          Wrap(
            spacing: 8,
            children: _availableRoles.map((role) {
              final isSelected = _selectedRoles.any((r) => r.id == role.id);
              return FilterChip(
                label: Text(role.name),
                selected: isSelected,
                onSelected: (selected) {
                  setState(() {
                    if (selected) {
                      _selectedRoles.add(role);
                    } else {
                      _selectedRoles.removeWhere((r) => r.id == role.id);
                    }
                  });
                },
              );
            }).toList(),
          ),
          const SizedBox(height: 16),
          
          // 状态开关
          SwitchListTile(
            title: const Text('是否启用'),
            value: _isActive,
            onChanged: (bool value) {
              setState(() {
                _isActive = value;
              });
            },
          ),
          const SizedBox(height: 24),
          
          // 提交按钮
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _submitForm,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 16.0),
                child: Text(widget.user == null ? '创建用户' : '更新用户'),
              ),
            ),
          ),
        ],
      ),
    );
  }
}